package com.swapper.math.utils;

public final class ColorUtils {
  private ColorUtils() {
    throw new UnsupportedOperationException(getClass().getSimpleName());
  }

  /**
   * 两种半透明的颜色叠加混合
   *
   * @param color1 半透明颜色1 argb
   * @param color2 半透明颜色2 argb
   * @return 混合后的半透明的颜色 argb
   */
  public static int mixtureAlpha1(int color1, int color2) {
    int red1 = color1 >> 16 & 0xff;
    int green1 = color1 >> 8 & 0xff;
    int blue1 = color1 & 0xff;
    int alpha1 = color1 >>> 24;
    int red2 = (color2 >> 16) & 0xff;
    int green2 = (color2 >> 8) & 0xff;
    int alpha2 = color2 >>> 24;
    int blue2 = color2 & 0xff;
    int alpha = 0xff - (0xff - alpha1) * (0xff - alpha2);
    int red = (red1 * alpha1 + red2 * alpha2 * (0xff - alpha1)) / alpha;
    int green = (green1 * alpha1 + green2 * alpha2 * (0xff - alpha1)) / alpha;
    int blue = (blue1 * alpha1 + blue2 * alpha2 * (0xff - alpha1)) / alpha;
    return 0xff000000 | (red << 16) | (green << 8) | blue;
  }

  /**
   * 假设有一幅纯色的不透明的图像A和另一幅纯色的半透明的图像B
   * 那么透过B去看A，看上去的C就是B和A的混合图象
   *
   * @param foreground 前景色，为半透明颜色 argb
   * @param background 背景色，为不透明颜色 rgb
   * @return 覆盖后的颜色，为不透明颜色 rgb
   */
  public static int mixtureAlphaBlend(int foreground, int background) {
    int alpha = foreground >>> 24;
    int backgroundR = background >> 16 & 0xff;
    int backgroundG = background >> 8 & 0xff;
    int backgroundB = background & 0xff;
    int foregroundR = (foreground >> 16) & 0xff;
    int foregroundG = (foreground >> 8) & 0xff;
    int foregroundB = foreground & 0xff;
    int red = (backgroundR * alpha + foregroundR * (0xff - alpha)) / 0xff;
    int green = (backgroundG * alpha + foregroundG * (0xff - alpha)) / 0xff;
    int blue = (backgroundB * alpha + foregroundB * (0xff - alpha)) / 0xff;
    return 0xff000000 | (red << 16) | (green << 8) | blue;
  }
}
